//
// Club Schema
//
var mongoose = require('mongoose');

var schema = mongoose.Schema({
   name           : String,
   description    : String,
   createddate    : Date,
   creator        : {type: mongoose.Schema.Types.ObjectId, ref: 'club.user'},
   members        : [{type: mongoose.Schema.Types.ObjectId, ref: 'club.user'}],
   zipcode        : String,
   lat            : Number,
   lng            : Number
});


schema.methods.print = function(){
   console.log(this.name);
};

/*
 before club is removed,
 1) Its owner's club will be null.
 2) It will be pulled from all its member' joinedclubs
*/
schema.pre('remove', function(next){
   console.log('PRE REMOVE CLUB');
   var club = this;
   // 1) 
   require('../club.domains').User.update({club: club}, {club: null}, function(err, num){
      if(err) throw err;
      // 2) using $pull operator
      require('../club.domains').User.update( {joinedclubs: club}, {$pull: {joinedclubs: club}}, {multi: true}, function(errr, num){
         if(errr) throw errr;
         next();
      });
   });
});


schema.post('save', function(doc){ // post has no next
   console.log('POST SAVE CLUB - function removed');
   //mongoose.model('club.user', userSchema).update({_id: this.creator}, {club : this._id} ,function(err, doc){ });
   //mongoose.model('club.user', userSchema).update({_id: this.creator}, {joinedclub : this._id} ,function(err, doc){ });
});

module.exports = schema;
